package fr.cie.blog.controller.results;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.ServletRedirectResult;

import com.opensymphony.xwork2.ActionInvocation;

/**
 * @author Jee3
 * 
 */
public class SamePageResult extends ServletRedirectResult {

	/**
	 * serialVersionUID.
	 */
	private static final long serialVersionUID = 1981637005849153642L;
	/**
	 * log.
	 */
	public static final Logger LOG = Logger.getLogger(SamePageResult.class);

	// private Map<String, Object> session;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.apache.struts2.dispatcher.ServletRedirectResult#doExecute(java.lang
	 * .String, com.opensymphony.xwork2.ActionInvocation)
	 */
	@Override
	protected final void doExecute(final String finalLocation,
			final ActionInvocation invocation) {
		LOG.info("works");

		final HttpServletRequest req = ServletActionContext.getRequest();
		// String loc = req.getRequestURL().toString();
		final String loc = req.getHeader("Referer");
		String finalLoc = loc;

		// If the user has just logged out, it avoids to log out just after
		// re-logging by redirecting to index action
		if (loc.contains("/logout")) {
			finalLoc = loc.replaceAll("logout", "index");
		}
		// TODO: mieux gérer cette situation (dans tiles ?)
		// If the user has just registered, it avoids to re-register just after
		// logging.
		if (loc.contains("/register")) {
			finalLoc = loc.replaceAll("register", "index");
		}
		try {
			super.doExecute(finalLoc, invocation);
		} catch (final Exception e) {
			LOG.error("erreur dans la méthode SamePageResult.doExecute", e);
		}

	}

	/*
	 * private DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
	 * 
	 * @Override protected void doExecute(String finalLocation, ActionInvocation
	 * invocation) throws Exception { String date = df.format(new Date());
	 * String loc = "/section/document/"+date; super.doExecute(loc, invocation);
	 * }
	 */

}
